package com.yifeng.repo.controller.postman.work.task;

import com.fasterxml.jackson.databind.JsonNode;
import com.yifeng.repo.base.utils.common.FirePreconditions;
import com.yifeng.repo.controller.postman.work.biz.BizCallbackAction;
import com.yifeng.repo.controller.postman.work.dto.HttpRequestParam;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by daibing on 2023/5/24.
 */
@Slf4j
public class HttpCallbackTask {
    private final HttpRequestParam callbackParam;
    private final BizCallbackAction bizCallbackAction;

    public HttpCallbackTask(HttpRequestParam callbackParam, BizCallbackAction bizCallbackAction) {
        this.callbackParam = callbackParam;
        this.bizCallbackAction = bizCallbackAction;
    }

    public String doRun() {
        // 1. 解析并且检查回调结果
        JsonNode output = bizCallbackAction.parseCallbackResult(callbackParam.getHeader(), callbackParam.getBody());
        FirePreconditions.checkState(
                bizCallbackAction.checkCallbackBody(output),
                String.format("Callback data is not ok: uri=%s, body=%s", callbackParam.getUri(), callbackParam.getBody()));
        FirePreconditions.checkState(
                bizCallbackAction.checkCallbackSign(output),
                String.format("Callback data is not safe: uri=%s, body=%s", callbackParam.getUri(), callbackParam.getBody()));

        // 2. 抽取回调数据并保存
        return bizCallbackAction.doSaveCallbackData(output);
    }
}
